<?php
namespace app\joybet\home;

use Facebook;

/**
 *
 */
class Oauth extends Common
{
    protected $uid;
    protected $fb_access_token;

    function __construct()
    {
        parent::__construct();

        if (!session_id()) {
            session_start();
        }

        // session('fb_access_token', null);
        if (!session('fb_access_token') || !session('uid')) {
            // halt(333);
            $this->fb = new Facebook\Facebook([
                'app_id' => $this->app_id, // Replace {app-id} with your app id
                'app_secret' => $this->app_secret,
                'default_graph_version' => 'v2.2',
            ]);

            if(input('code')){
                $this->callBack();
            }else{
                $this->login();
            }
        }

        $this->uid = session('uid');
        $this->fb_access_token = session('fb_access_token');

    }

    protected function login()
    {
        $fb = $this->fb;
        $helper = $fb->getRedirectLoginHelper();
        // $permissions = ['email']; // Optional permissions
        $loginUrl = $helper->getLoginUrl($this->request->url(true));
        return $this->redirect($loginUrl);
        // echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
        // exit;
    }

    protected function callBack()
    {
        $fb = $this->fb;
        $helper = $fb->getRedirectLoginHelper();

        try {
            $accessToken = $helper->getAccessToken();
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            // When validation fails or other local issues
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

        if (! isset($accessToken)) {
            if ($helper->getError()) {
                header('HTTP/1.0 401 Unauthorized');
                echo "Error: " . $helper->getError() . "\n";
                echo "Error Code: " . $helper->getErrorCode() . "\n";
                echo "Error Reason: " . $helper->getErrorReason() . "\n";
                echo "Error Description: " . $helper->getErrorDescription() . "\n";
            } else {
                header('HTTP/1.0 400 Bad Request');
                echo 'Bad request';
            }
            exit;
        }

        // Logged in
        // echo '<h3>Access Token</h3>';
        // var_dump($accessToken->getValue());

        // // The OAuth 2.0 client handler helps us manage access tokens
        $oAuth2Client = $fb->getOAuth2Client();

        // // Get the access token metadata from /debug_token
        $tokenMetadata = $oAuth2Client->debugToken($accessToken);
        // echo '<h3>Metadata</h3>';
        // var_dump($tokenMetadata);

        // Validation (these will throw FacebookSDKException's when they fail)
        $tokenMetadata->validateAppId($this->app_id); // Replace {app-id} with your app id
        // If you know the user ID this access token belongs to, you can validate it here
        //$tokenMetadata->validateUserId('123');
        $tokenMetadata->validateExpiration();

        if (! $accessToken->isLongLived()) {
                  // Exchanges a short-lived access token for a long-lived one
            try {
                $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
            } catch (Facebook\Exceptions\FacebookSDKException $e) {
                echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
                exit;
            }
        }

        $access_token = $accessToken->getValue();
        session('fb_access_token', $access_token);

        $member_info = $this->getMemberInfo($access_token);
        $member_id = $this->addMember($member_info);
        session('uid', $member_id);
        
        // User is logged in with a long-lived access token.
        // You can redirect them to a members-only page.
        //header('Location: https://example.com/members.php');
    }

    protected function getMemberInfo($access_token)
    {
        try {
        // Returns a `Facebook\FacebookResponse` object
            $response = $this->fb->get('/me?fields=id,name,picture.height(200)', $access_token);
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

        return $member_info = $response->getGraphUser();
    }

    protected function addMember($member_info)
    {
        $member = model('joybet_member');
        $exist_member = $member->where(['fbid' => $member_info['id']])->find();

        $member_info = [
            'fbid' => $member_info['id'],
            'name' => $member_info['name'],
            'picture' => $member_info['picture']['url']
        ];

        if ($exist_member) {
            $member->save($member_info, ['fbid' => $member_info['fbid']]);
            return $exist_member['id'];
        }else{
            $member->save($member_info);
            return $member->id;
        }
        
    }
}
